#!/usr/bin/env python
# coding: utf-8

from xml.etree.ElementTree import ElementTree
import gtk,gtk.glade
import os

from wordpath import *
from widgets import show_info
from recite import Recite
from parse import Parse

# 多变量同时定义
(
    COLUMN_WORD,
    COLUMN_MEANING,
) = range(2)

(
    COLUMN_DIR,
    COLUMN_PATH
) = range(2)

class WordsList():
    """创建单词列表
    """
    def __init__(self, wTree):
        self.treeview_words = wTree.get_widget("treeview_words")

        # 列类型
        liststore = gtk.ListStore(COLUMN, COLUMN)
        # 设置列类型
        self.treeview_words.set_model(liststore)

        # 添加二列标题
        self.__add_title_column("单词", COLUMN_WORD)
        self.__add_title_column("解释", COLUMN_MEANING)

    # 增加列
    def __add_title_column(self, title, column_id):
        column = gtk.TreeViewColumn(title, gtk.CellRendererText(), text = column_id)
        column.set_resizable(True)      # 可改变大小
        column.set_sort_column_id(column_id) # 可排序
        self.treeview_words.append_column(column)

    # 创建单词列表
    def create_words_list(self, grade_file, model):
        # 添加
        pa = Parse(grade_file)          # 定义一个解析对象
        words_list = pa.mean_summary()
        # print words_list
        for i in range(100):
            li_iter = model.append()
            model.set(li_iter,
                      COLUMN_WORD, words_list[i]['name'],
                      COLUMN_MEANING, words_list[i]['meaning'])

class GradeTree():
    """建立一个等级的树结构
    参数：
    wTree: 树型结构的widgets
    wordslist: 一个Wordslist对象
    dir: 等级的总目录
    """
    def __init__(self, wTree, wordslist, dir=BOOK_PATH):
        self.wTree = wTree
        self.treeview_grade = self.wTree.get_widget("treeview_grade")
        self.treestore = gtk.TreeStore(COLUMN, COLUMN)

        # 添加标题头
        self.__add_header()

        piter = self.treestore.append(None)       # 父，返回一个gtk.TreePiter对象
        
        # 设置系统等级
        self.treestore.set(piter, COLUMN_DIR, "WordJoy")

#         # 添加列，piter为父亲
#         child_iter = self.treestore.append(piter) # 子项
#         # 添加进用户的书本
#         mybookdir = os.path.join(os.path.expanduser("~"),".wordjoy/books")
#         # 添加内容
#         self.treestore.set(child_iter,
#             COLUMN_DIR, "我的生词库",
#             COLUMN_PATH, mybookdir)
#         # 自定义书本
#         self.__create_model(mybookdir, self.treestore, piter)

        self.treeview_grade.set_model(self.treestore)
        
        # 创建系统等级树
        self.__create_model(dir, self.treestore, piter)
        
        # 界面：展开所有
        self.treeview_grade.expand_all()

        # 获得当前选中的条，返回gtk.TreeSelection对象
        selection = self.treeview_grade.get_selection()
        # 设置选中样式
        selection.set_mode(gtk.SELECTION_SINGLE)
        # 信号/回调函数，参数为wordslist
        selection.connect("changed", self.selection_changed, wordslist)
        selection.select_iter(self.treestore.iter_children(self.treestore.get_iter_first()))

        # OK按钮
        button_choose = self.wTree.get_widget("button_choose")
        button_choose.connect("clicked", self.__on_button_clicked)

    # 单击OK
    def __on_button_clicked(self, widget):
        """功能：
        1、跳转到“单词初记”
        2、开始开始”单词初记“
        """
        sidebar = self.wTree.get_widget("sidebar_notebook")

        # 当前选中
        if not os.path.isdir(self.dir_file):
            #print self.dir_file
            sidebar.set_current_page(2)   # 自动跳转到页面“单词初记”去
            Recite(self.dir_file, self.wTree) # 调用单词初记功能
        else:
            show_info("请选择一个等级！")
    
    # 添加树的标题
    def __add_header(self):
        model = self.treeview_grade.get_model()
        # 创建一个gtk.TreeViewColumn对象
        # gtk.CellRendererText对象，属性＝列
        column = gtk.TreeViewColumn("等级选择", gtk.CellRendererText(), text = 0)
        self.treeview_grade.append_column(column)

    # 创建模型
    def __create_model(self, dir, model, piter):
        for item in os.listdir(dir):
            fullname = os.path.join(dir, item)
            if os.path.isdir(fullname):
                # 添加项目
                child_iter = model.append(piter)
                model.set(child_iter, COLUMN_DIR, item, COLUMN_PATH, fullname)
                self.__create_model(fullname, model, child_iter) # 递归创建树
            else:
                item = item.split('.')[0]  # 去掉文件后缀名
                child_iter = model.append(piter)
                model.set(child_iter, COLUMN_DIR, item, COLUMN_PATH, fullname)

    # 单击树的条目时，触发事件
    def selection_changed(self, widget, wordslist):
        (tree_model, tree_iter) = widget.get_selected()
        self.dir_file = tree_model.get_value(tree_iter, COLUMN_PATH) # 单击ok时，用到self.dir_file
        if not os.path.isdir(self.dir_file): # 等级文件
            model = wordslist.treeview_words.get_model()
            model.clear()               # 清除？
            self.__set_copyleft(self.dir_file)                # 设置非版权信息
            wordslist.create_words_list(self.dir_file, model) # 创建单词列表

    # 设置非版权信息
    def __set_copyleft(self, grade_file):
        label_copyleft = self.wTree.get_widget("label_copyleft")
        copyleft = []
        tree = ElementTree()
        tree.parse(grade_file)
        head = tree.getiterator("head")
        head_child = head[0].getchildren()
        for item in head_child:
            copyleft.append(item.text)
        copyleft = "等级名：" + copyleft[0]  \
                   + '\n单词数：' + copyleft[1] \
                   + '\n作者：' + copyleft[2] \
                   + '\n日期：' + copyleft[3]
        label_copyleft.set_label(copyleft)


class ChooseGrade():
    def __init__(self, wTree):
        """功能：实现选择等级，调用了WordsList和GradeTree类
        参数：wTree
        """

        # 生成一个单词列表对象
        wordslist = WordsList(wTree)
        # 生成左边的等级树，实现事件
        GradeTree(wTree, wordslist)

        
if __name__ == "__main__":
    wTree = gtk.glade.XML(GLADE_PATH + "choose_test.glade")

    events_dic = {"on_window_choose_destroy":gtk.main_quit}
    wTree.signal_autoconnect(events_dic)

    ChooseGrade(wTree)
    gtk.main()
